<template>
  <div class="meeting-appointment">
    <div class="box-head">
      <div class="select">
        <div class="head-label">会议时间</div>
        <div class="head-date">
          <el-date-picker
            v-model="meetingDate"
            type="date"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            size="small"
            :editable="false"
            :clearable="false"
            @change="onDateChange"></el-date-picker>
        </div>
        <div class="head-time">
          <el-time-select
            placeholder="起始时间"
            v-model="startTime"
            :picker-options="{
              start: '08:00',
              step: '00:30',
              end: '20:00',
            }"
            size="small"
            @change="onChange()"
            :clearable="false"></el-time-select>
          <el-time-select
            placeholder="结束时间"
            v-model="endTime"
            :picker-options="{
              start: '08:00',
              step: '00:30',
              end: '20:00',
              minTime: startTime,
            }"
            size="small"
            @change="onChange()"
            :clearable="false"></el-time-select>
        </div>
      </div>
      <div class="button">
        <el-button type="primary" size="small" @click="toSubmit">确 定</el-button>
      </div>
    </div>
    <div class="list_con">
      <div class="legend">
        <div><b>图例</b></div>
        <div>
          <span class="empty"></span>
          空闲
        </div>
        <div>
          <span class="use"></span>
          占用
        </div>
      </div>
      <div class="tab_box">
        <div class="tab_left">
          <el-radio-group v-model="meetingChoose" size="small" @input="onChange">
            <div class="radio_li" v-for="item in meetPlaceList" :key="item.roomId">
              <el-radio :label="item.roomId" border>
                {{ item.roomName }}
              </el-radio>
            </div>
          </el-radio-group>
        </div>
        <div class="tab_right">
          <div class="th_row">
            <div class="box_row" v-for="(row, index) in timeList" :key="index">{{ row }}</div>
          </div>
          <div class="tr_row" id="tr_row" ref="tr_row">
            <div class="box_row" v-for="(row, index) in timeList.length * 2" :key="index">
              <div
                class="box_col"
                v-for="(col, i) in meetPlaceList"
                :key="i"
                :data-id="String(index) + String(i)"
                :ref="'box_col' + String(index) + String(i)"
                @mousedown="onMouseDown($event, index, i)"></div>
            </div>
            <div
              class="box_meet"
              :style="getStyle(item, index)"
              v-for="(item, index) in tableData"
              :key="item.id"></div>
            <div class="box_choose" ref="box_choose"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getMeetingRoomList, checkRoomAndTimeAuthority } from '@apis/meeting.js'
import moment from 'moment'
moment.locale('zh-cn')
export default {
  name: 'MeetRoom',
  components: {},
  props: {
    meetData: {
      type: Object,
      default: () => {
        return {
          id: '',
        }
      },
    },
    roomInfo: {
      type: Object,
      default: () => {},
    },
    meetId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      moment: moment,
      meetingDate: moment().format('YYYY-MM-DD'),
      startTime: '',
      endTime: '',
      meetPlaceList: [],
      pickerOptions: {
        disabledDate(time) {
          return moment(time).format('YYYYMMDD235959') < moment().format('YYYYMMDDHHmmss')
        },
      },
      meetingChoose: '',
      timeList: [
        '08:00',
        '09:00',
        '10:00',
        '11:00',
        '12:00',
        '13:00',
        '14:00',
        '15:00',
        '16:00',
        '17:00',
        '18:00',
        '19:00',
        // '20:00',
      ],
      timeListA: [
        '08:00',
        '08:30',
        '09:00',
        '09:30',
        '10:00',
        '10:30',
        '11:00',
        '11:30',
        '12:00',
        '12:30',
        '13:00',
        '13:30',
        '14:00',
        '14:30',
        '15:00',
        '15:30',
        '16:00',
        '16:30',
        '17:00',
        '17:30',
        '18:00',
        '18:30',
        '19:00',
        '19:30',
        '20:00',
      ],
      tableData: [],
      mouseDownInfo: {
        xBox: 0,
        yBox: 0,
        xPoint: 0,
        disL: 0,
        disR: 0,
      },
      boxInfo: {
        xBox: 0,
        yBox: 0,
      },
      mouseUpX: 0,
      isChoose: false,
      isMove: false,
    }
  },
  watch: {},
  computed: {},
  created() {},
  mounted() {
    this.getMeetingRoomList()
  },
  methods: {
    getMeetingRoomList() {
      getMeetingRoomList({
        date: this.meetingDate,
        meetingId: this.meetId || '',
      }).then(res => {
        if (res.code === 0) {
          this.meetPlaceList = res.data
          const table = []
          for (let i = 0; i < res.data.length; i++) {
            const el = res.data[i]
            if (el.appointHistoryList.length) {
              el.appointHistoryList.forEach(item => {
                const arr = item.split('-')
                const Xindex1 = this.timeListA.findIndex(li => {
                  return li === arr[0]
                })
                const Xindex2 = this.timeListA.findIndex(li => {
                  return li === arr[1]
                })
                table.push({
                  Xindex1,
                  Xindex2,
                  Yindex: i,
                })
              })
            }
          }
          this.$nextTick(() => {
            this.tableData = table
            if (this.roomInfo && this.roomInfo.roomId) {
              this.meetingChoose = this.roomInfo.roomId
              this.startTime = this.roomInfo.startTime
              this.endTime = this.roomInfo.endTime
              this.onChange()
            }
          })
        }
      })
    },
    toSubmit() {
      if (!this.isChoose) {
        return this.$message.warning('请选择会议时间')
      }
      if (!this.meetingChoose) {
        return this.$message.warning('请选择会议室')
      }
      const idx = this.meetPlaceList.findIndex(item => {
        return item.roomId === this.meetingChoose
      })
      if (idx !== this.mouseDownInfo.yBox) {
        return this.$message.warning('请对应选择会议室及会议室时间')
      }
      const startTime = this.meetingDate + ' ' + this.startTime + ':00'
      const endTime = this.meetingDate + ' ' + this.endTime + ':00'
      if (moment(startTime).format('YYYYMMDDHHmmss') < moment().format('YYYYMMDDHHmmss')) {
        this.$confirm('会议开始时间小于当前时间，确定要提交吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info',
        })
          .then(() => {
            this.submitChoose(idx, startTime, endTime)
          })
          .catch()
      } else {
        this.submitChoose(idx, startTime, endTime)
      }
    },
    onDateChange() {
      this.getMeetingRoomList()
    },
    getStyle(item, idx) {
      // console.log(item)
      const allWidth = document.getElementById('tr_row').offsetWidth
      const copies = this.timeList.length * 2
      const top = item.Yindex * 50 + 'px'
      const left = (allWidth / copies) * item.Xindex1 - 1 + 'px'
      const width = (allWidth / copies) * (item.Xindex2 - item.Xindex1) + 'px'
      return `top:${top};width:${width};left:${left};`
    },
    onMouseDown(e, idx1, idx2) {
      const box = this.$refs.tr_row
      this.boxInfo = {
        xBox: box.getBoundingClientRect().left,
        yBox: box.getBoundingClientRect().right,
      }

      const boxCol = this.$refs['box_col' + String(idx1) + String(idx2)][0]
      const boxColInfo = {
        xBox: boxCol.getBoundingClientRect().x,
        yBox: boxCol.getBoundingClientRect().x + boxCol.getBoundingClientRect().width,
      }
      const disX = e.clientX - this.boxInfo.xBox

      this.mouseDownInfo = {
        xBox: idx1,
        yBox: idx2,
        xPoint: disX,
        disL: e.clientX - boxColInfo.xBox,
        disR: boxColInfo.yBox - e.clientX,
      }
      box.onmousemove = ee => {
        this.isMove = true
        this.onMouseMove(ee, disX)
      }
      window.onmouseup = () => {
        box.onmousemove = null
        window.onmouseup = null
        if (this.isMove) {
          /* 鼠标点击方格所在列表的索引 x，y */
          // const xBox = this.mouseDownInfo.xBox
          const yBox = this.mouseDownInfo.yBox
          const arr = this.tableData.filter(item => {
            return yBox === item.Yindex && this.mouseUpX > item.Xindex1 && this.mouseUpX < item.Xindex2
          })
          this.judgeRoomTable(arr)
        } else {
          this.isMove = false
        }
      }
    },
    onMouseMove(e, disX) {
      /* 获取每一格的宽度 */
      const allWidth = document.getElementById('tr_row').offsetWidth
      const copies = this.timeList.length * 2
      const simpleWidth = allWidth / copies

      /* 鼠标点击方格所在列表的索引 x，y */
      const xBox = this.mouseDownInfo.xBox
      const yBox = this.mouseDownInfo.yBox

      /* 获取鼠标移动的距离 */
      const disXB = e.clientX - this.boxInfo.xBox
      const left = disXB - disX
      if (left > 0) {
        const moveX = left + this.mouseDownInfo.disL
        let moveNum = Math.round(moveX / simpleWidth)
        if (xBox + moveNum > copies) {
          moveNum = copies - xBox
        }
        this.$refs.box_choose.style.width = moveNum * simpleWidth + 'px'
        this.$refs.box_choose.style.left = simpleWidth * xBox - 1 + 'px'
        this.$refs.box_choose.style.top = 50 * yBox + 5 + 'px'
        this.isChoose = moveNum > 0
        this.mouseUpX = xBox + moveNum
      } else {
        const moveX = 0 - left + this.mouseDownInfo.disR
        let moveNum = Math.round(moveX / simpleWidth)
        if (xBox - moveNum <= 0) {
          moveNum = xBox
        }
        this.$refs.box_choose.style.width = moveNum * simpleWidth + 'px'
        this.$refs.box_choose.style.left = simpleWidth * (xBox - moveNum) - 1 + 'px'
        this.$refs.box_choose.style.top = 50 * yBox + 5 + 'px'
        this.isChoose = moveNum > 0
        this.mouseUpX = xBox - moveNum
      }
    },
    judgeRoomTable(arr) {
      if (arr.length > 0) {
        this.$alert('该时间段内会议室已被占用，', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.clearRoom()
            this.isMove = false
          },
        })
      } else {
        this.meetingChoose = this.meetPlaceList[this.mouseDownInfo.yBox].roomId
        if (this.mouseUpX > this.mouseDownInfo.xBox) {
          this.startTime = this.timeListA[this.mouseDownInfo.xBox]
          this.endTime = this.timeListA[this.mouseUpX]
        } else {
          this.startTime = this.timeListA[this.mouseUpX]
          this.endTime = this.timeListA[this.mouseDownInfo.xBox]
        }
        this.isMove = false
      }
    },
    clearRoom() {
      this.meetingChoose = ''
      this.mouseUpX = 0
      this.isChoose = false
      this.$refs.box_choose.style.width = 0
      this.$refs.box_choose.style.left = 0
      this.$refs.box_choose.style.top = 0
    },
    onChange() {
      if (!this.startTime || !this.endTime) return
      const startX = this.timeListA.findIndex(item => {
        return item === this.startTime
      })
      const endX = this.timeListA.findIndex(item => {
        return item === this.endTime
      })
      if (this.meetingChoose) {
        const timeY = this.meetPlaceList.findIndex(item => {
          return item.roomId === this.meetingChoose
        })
        const arr = this.tableData.filter(item => {
          return (
            timeY === item.Yindex &&
            ((endX > item.Xindex1 && startX <= item.Xindex1) || (startX < item.Xindex2 && endX >= item.Xindex2))
          )
        })
        this.judgeRoomSelect(arr, timeY, startX, endX)
      }
    },
    judgeRoomSelect(arr, yBox, startX, endX) {
      if (arr.length > 0) {
        this.$alert('该时间段内会议室已被占用，', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.clearRoom()
          },
        })
      } else {
        /* 获取每一格的宽度 */
        const allWidth = document.getElementById('tr_row').offsetWidth
        const copies = this.timeList.length * 2
        const simpleWidth = allWidth / copies

        this.isChoose = true
        this.$refs.box_choose.style.width = (endX - startX) * simpleWidth + 'px'
        this.$refs.box_choose.style.left = simpleWidth * startX - 1 + 'px'
        this.$refs.box_choose.style.top = 50 * yBox + 5 + 'px'
      }
    },
    submitChoose(idx, startTime, endTime) {
      const param = {
        endTime: endTime,
        meetingId: this.meetData.id || '',
        roomId: this.meetingChoose,
        roomName: this.meetPlaceList[idx].roomName,
        startTime: startTime,
      }
      checkRoomAndTimeAuthority(param).then(res => {
        if (res.code === 0 && res.data === '1') {
          this.$emit('appointmentSuccess', param)
        } else {
          this.$message.warning(res.data)
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.meeting-appointment {
  user-select: none;
  padding: 0 15px;
  height: 100%;
  .el-input__inner {
    border: 1px solid #dcdfe6;
  }
  .el-date-editor {
    width: auto;
  }
  .box-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .select {
      display: flex;
      align-items: center;
    }
    .head-label {
      font-weight: 600;
      margin-right: 20px;
    }
  }
  .list_con {
    margin-top: 20px;
    position: relative;
    .legend {
      position: absolute;
      top: 0;
      left: 0;
      display: flex;
      align-items: center;
      height: 30px;
      div {
        display: flex;
        align-items: center;
      }
      .empty,
      .use {
        display: block;
        height: 20px;
        width: 30px;
        border: 1px solid #d0d7e0;
        margin: 0 10px;
      }
      .use {
        background-color: #d0d7e0;
        opacity: 0.7;
      }
    }
    .tab_box {
      display: flex;
      .tab_left {
        width: 200px;
        margin-top: 40px;
        margin-right: 10px;
        /deep/.el-radio-group {
          display: flex;
          flex-direction: column;
          .radio_li {
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .el-radio {
            width: 100%;
            margin-left: 0 !important;
            display: flex;
            align-items: center;
            height: 40px;
            .el-radio__label {
              white-space: pre-wrap;
              line-height: 15px;
            }
            &.is-bordered {
              padding: 0 8px;
            }
          }
        }
      }
      .tab_right {
        width: calc(100% - 210px);
        .th_row {
          display: flex;
          align-items: center;
          border-top: 1px solid #d0d7e0;
          border-left: 1px solid #d0d7e0;
          .box_row {
            flex: 1;
            text-align: center;
            height: 30px;
            line-height: 30px;
            border-right: 1px solid #d0d7e0;
            border-bottom: 1px solid #d0d7e0;
          }
        }
        .tr_row {
          display: flex;
          border-top: 1px solid #d0d7e0;
          border-left: 1px solid #d0d7e0;
          margin-top: 10px;
          position: relative;
          width: 100%;
          .box_row {
            flex: 1;
            text-align: center;
            box-sizing: border-box;
            .box_col {
              width: 100%;
              border-right: 1px solid #d0d7e0;
              border-bottom: 1px solid #d0d7e0;
              height: 50px;
              line-height: 50px;
              box-sizing: border-box;
            }
          }
          .box_meet {
            position: absolute;
            background-color: #d0d7e0;
            height: 50px;
            min-height: 50px;
            opacity: 0.7;
            box-sizing: border-box;
            // border: 1px solid #d0d7e0ad;
          }
          .box_choose {
            position: absolute;
            background-color: #66b1ff;
            height: 40px;
            min-height: 40px;
            opacity: 0.7;
            box-sizing: border-box;
            border-radius: 4px;
          }
        }
      }
    }
  }
}
</style>
